import java.util.Arrays;

import sun.net.www.content.text.plain;


public class BM {
    //可利用资源矩阵
    public int[][] available;
    //需求矩阵
    public int[][]need;
    //分配矩阵
    public int[][]allocation;
    public int[][]max;

    public int []safeProcess;
    int curP=1;
    int safeProcessSize=0;
    BM(int[][] available,int[][]need,int[][]allocation,int[][]max){
        this.available=available;
        this.need=need;
        this.allocation=allocation;
        this.max=max;
        this.safeProcess=new int[max.length];
    }
    public void init(){
       this.safeProcessSize=1;
       this.safeProcess[0]=0;
       while(this.safeProcessSize!=this.max.length){

            if (!this._pExistInSafeProcessTable(this.curP)&&this._isavaLargerNeed(this._getNeedByP(this.curP), this._getLatestAvailable())) {
                  this._updateLatestAvailable(this.curP, this._getLatestAvailable());
                  this._addSafeProcess(this.curP);
                resetCurP();
            }else{
                this.curP++;
            }
         
    
       }
    }
    public void resetCurP(){
        this.curP=1;
    }
    //更新available
    public void _updateLatestAvailable(int p,int []latestAvailable){
        int []arr=this._arrAdd(this._getAllocationByP(p), latestAvailable);

        for (int i = 0; i < arr.length; i++) {
            this.available[p][i]=arr[i];
        }
    }

    //find 最新的available
    public int[] _getLatestAvailable(){
        System.out.println(Arrays.toString(this.safeProcess));
        System.err.println(this.safeProcessSize);
        int safeProcessId=this.safeProcess[this.safeProcessSize-1];
     
        return this.available[safeProcessId];
    }
    //数组相加
    public int[] _arrAdd(int []a,int[]b){
        int []c=new int[a.length];
        for (int i = 0; i < a.length; i++) {
            c[i]=a[i]+b[i];
        }
        return c;
    }
    //获取Need数组
    public int[] _getNeedByP(int p){
        return this.need[p];
    }
    //获取allocation数组
    public int[] _getAllocationByP(int p){
        return this.allocation[p];
    }
    //新增安全进程
    public void _addSafeProcess(int p){
            this.safeProcess[this.safeProcessSize++]=p;
    }
    //是否大于need
    public boolean _isavaLargerNeed(int []need,int []available){
        for(int i=0;i<need.length;i++){
            if (need[i]>available[i]) {
                return false;
            }
        }
        return true;
    }

    //判断pid是否已存放在安全进程中
    public boolean _pExistInSafeProcessTable(int p){
        for (int i : this.safeProcess) {
            if (i==p) {
                return true;
            }
        }
        return false;
    }
}